﻿using LuShanTea.Common;
using LuShanTea.DTO;
using LuShanTea.Front.Web.App_Start;
using LuShanTea.Front.Web.Models;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Front.Web.Controllers
{

    public class UserController : Controller
    {
        public const string USERIMGSRC = "UserImgSrc";

        public IUserService UserService { get; set; }

        public IOrderService OrderService { get; set; }

        public IOrderRecordService OrderRecordService { get; set; }

        public ICollectService CollectService { get; set; }

        public IIdNameService IdNameService { get; set; }

        public IGoodService GoodService { get; set; }

        public IGoodImsSrcService GoodImsSrcService { get; set; }

        public ICommentService CommentService { get; set; }

        private UserDataHelper _userHelper = new UserDataHelper();

        [IsLogin]
        // GET: User
        public ActionResult Index()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }

            #region 获取订单完成和未付款数
            var orderStatus = IdNameService.GetNameByTypeName("订单状态");

            //获取已评论的状态Id
            long completeOrderId = orderStatus.Where(s => s.Name == "已收货").SingleOrDefault().Id;

            //获取未付款的状态Id
            long inPayId = orderStatus.Where(s => s.Name == "未付款").SingleOrDefault().Id;

            //获取完成订单数
            long completeOrdeCount = OrderService.GetCountByUser(userid, completeOrderId);

            //获取未付款订单
            long inPayOrderCount = OrderService.GetCountByUser(userid, inPayId);

            #endregion

            SetUserInfo(user);

            UserCenterInfoModel model = new UserCenterInfoModel();

            model.CompleteOrdeCount = completeOrdeCount;
            model.InPayOrderCount = inPayOrderCount;

            //获取Redis缓存数据
            using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("47.106.159.212:6379"))
            {
                IDatabase db = connection.GetDatabase();//默认是访问 db0 数据库，可以通过方法参数指定数字访问不同的数据库
                RedisHelper redis = new RedisHelper(db);
                var userCollectModel = redis.Get<UserCollectModel>("LuShanTea_Order_UserCollectModel_userid_" + userid);
                var userOrderRecords = redis.Get<UserOrderRecordModel>("LuShanTea_Order_UserOrderRecords_userid_" + userid);

                int orderRecordCount = 0;
                if (!int.TryParse(redis.Get("LuShanTea_Order_OrderRecordCount_userid_" + userid), out orderRecordCount))
                {
                    orderRecordCount = 0;
                }

                ViewBag.OrderRecordCount = orderRecordCount;

                if (userCollectModel == null)
                {
                    model.UserCollectModels = _userHelper.GetUserCollectModel(userid);
                }
                else
                {
                    model.UserCollectModels = userCollectModel;
                }


                if (userOrderRecords == null)
                {
                    model.UserOrderRecordModels = _userHelper.GetOrderRecords(userid, HttpContext, ViewData);
                }
                else
                {
                    model.UserOrderRecordModels = userOrderRecords;
                }
            }

            //model.UserCollectModels = _userHelper.GetUserCollectModel(userid);
            //model.UserOrderRecordModels = _userHelper.GetOrderRecords(userid, HttpContext, ViewData);

            return View(model);
        }

        [IsLogin]
        public ActionResult UserInfo()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }

            //清除用户上传头像的地址
            Session[USERIMGSRC] = null;

            SetUserInfo(user);

            return View(user);
        }

        [IsLogin]
        [HttpPost]
        public ActionResult UserInfoEdit(UserEditModel model)
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //验证上传数据
            if (!ModelState.IsValid)
            {
                string[] errors = MVCHelper.GetValidMsg(ModelState).Split('\r');
                return Json(new AjaxResult { Status = "error", ErrorMsg = errors[0] });
            }

            //获取用户
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "登录过时" });
            }

            //判断手机号或者邮箱是否已存在
            var dataUser = UserService.GetByPhoneNum(model.PhoneNumber);
            if (dataUser != null && dataUser.Id != userid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "手机号已存在" });
            }

            dataUser = UserService.GetByEmail(model.Email); ;
            if (dataUser != null && dataUser.Id != userid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "邮箱已存在" });
            }

            //创建 更新对象 实例
            UserUpdateDTO userUpate = new UserUpdateDTO();
            userUpate.Id = userid;
            userUpate.Email = model.Email;
            userUpate.PhoneNum = model.PhoneNumber;
            userUpate.Gender = model.Gender == 1 ? true : false;
            userUpate.Name = model.Name;
            userUpate.NickName = model.NiceName;
            userUpate.ImgSrc = (string)(Session[USERIMGSRC] ?? user.ImgSrc);

            UserService.Update(userUpate);

            return Json(new AjaxResult { Status = "ok" });
        }

        [IsLogin]
        public ActionResult UpdatePassword()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }
            SetUserInfo(user);
            return View();
        }

        [IsLogin]
        [HttpPost]
        public ActionResult UpdatePassword(UserUpdatePasswordModel model)
        {
            //验证提交数据
            if (!ModelState.IsValid)
            {
                string errors = MVCHelper.GetValidMsg(ModelState);
                return Json(new AjaxResult { Status = "error", ErrorMsg = errors });
            }

            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "登录过时" });
            }

            if (!UserService.UpdatePwd(userid, model.Password, model.NewPassword))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "原密码错误！" });
            }

            return Json(new AjaxResult { Status = "ok" });
        }

        [IsLogin]
        public ActionResult UserOrder()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }


            ViewBag.OrderCount = OrderService.GetCountByUser(userid, null);

            SetUserInfo(user);

            return View();
        }

        [IsLogin]
        [HttpPost]
        public ActionResult UserOrder(int currentIndex)
        {
            if (currentIndex <= 0 || currentIndex >= int.MaxValue)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "not page data"
                });
            }

            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "没有登录"
                });
            }

            //获取订单数据
            int pageSize = 2;

            var orders = OrderService.GetPageDataOrderByUserId(userid, pageSize, currentIndex)
                            .ToArray();

            int length = orders.Length;

            if (length <= 0)
            {
                return Json(new AjaxResult { Status = "not", ErrorMsg = "还没有订单" });
            }

            //此处count 无用，是因为当初GetUserOrderRecor抽取出来GetOrderRecords使用的
            int count = 0;

            var models = _userHelper.GetUserOrderRecor(orders, out count);

            return Json(new AjaxResult { Status = "ok", Data = models });
        }

        [IsLogin]
        public ActionResult UserCollect()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }


            ViewBag.OrderCount = OrderService.GetCountByUser(userid, null);

            SetUserInfo(user);

            var models = _userHelper.GetUserCollectModel(userid);

            return View(models);
        }

        [IsLogin]
        // 软删除
        [HttpPost]
        public ActionResult CollectDelete(long collectId)
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "没有登录"
                });
            }

            CollectService.MakeDelete(collectId);
            return Json(new AjaxResult { Status = "ok" });
        }

        [IsLogin]

        public ActionResult UserComment()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }

            SetUserInfo(user);

            ViewBag.CommentCount = CommentService.GetTotalCountByUser(userid);

            return View();
        }

        [IsLogin]
        [HttpPost]
        public ActionResult UserComment(int currentIndex)
        {
            if (currentIndex <= 0 || currentIndex >= int.MaxValue)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "not page data"
                });
            }

            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "没有登录"
                });
            }

            CommentDTO[] comments = CommentService.GetPageDataCommentByUserId(userid, currentIndex, 3);

            return Json(new AjaxResult { Status = "ok", Data = comments });


        }

        [IsLogin]
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "没有登录"
                });
            }

            if (file.ContentLength <= 0 || file.ContentLength >= 1024 * 1024 * 2)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "文件过大或过小" });
            }

            string md5 = CommonHelper.CalcMD5(file.InputStream);
            string ext = Path.GetExtension(file.FileName);

            string[] exts = { ".jpg", ".png", "gif", ".jpeg", ".bmp" };

            if (!exts.Contains(ext))
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "请勿上传非图片文件,支持格式( .jpg, .png, gif, .jpeg, .bmp)"
                });
            }

            string path = "upload/userImg/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + ext;

            //缩略图地址 150*150
            //string thumbPath = path + @"?imageView2/2/w/200/h/200/interlace/1/q/100" ;


            //string fullPath = HttpContext.Server.MapPath("~" + path);
            //string thumbFullPath = HttpContext.Server.MapPath("~" + thumbPath);


            //指针归零
            file.InputStream.Position = 0;

            UploadFile uploadFile = new UploadFile();

            AjaxResult ajaxResult = uploadFile.UploadImg(path, file.InputStream);

            //保存用户上传的头像
            Session[USERIMGSRC] = path;

            #region 本地存储
            //创建目录
            //new FileInfo(fullPath).Directory.Create();
            ////指针归零
            //file.InputStream.Position = 0;

            ////缩略图
            //ImageProcessingJob jobThumb = new ImageProcessingJob();
            //jobThumb.Filters.Add(new FixedResizeConstraint(150, 150));//缩略图尺寸 200*200 
            //jobThumb.SaveProcessedImageToFileSystem(file.InputStream, thumbFullPath);

            //file.InputStream.Position = 0;
            //file.SaveAs(fullPath);
            #endregion

            return Json(new AjaxResult { Status = "ok", Data = path });
        }

        private void SetUserInfo(UserDTO user)
        {
            ViewBag.User = user;
        }


        ///// <summary>
        ///// 用户收藏的商品
        ///// </summary>
        ///// <param name="userid"></param>
        ///// <returns></returns>
        //private UserCollectModel[] GetUserCollectModel(long userid)
        //{
        //    #region 我的收藏
        //    var collects = CollectService.GetCollectsByUserId(userid, 1, 5);

        //    //获取收藏的id
        //    long[] collectIds = collects.Select(c => c.Id).ToArray();

        //    //获取所有收藏商品的id
        //    long[] goodIds = collects.Select(c => c.GoodId).ToArray();

        //    List<UserCollectModel> listUserCollectModels = new List<UserCollectModel>();

        //    int index = 0;

        //    //遍历我收藏的商品Id
        //    foreach (long goodid in goodIds)
        //    {

        //        var good = GoodService.GetByGoodId(goodid);

        //        //获取商品第一张图片的地址
        //        GoodImgSrcDTO goodImgSrcDTO = GoodImsSrcService.GetFirstImgByGoodId(goodid);

        //        string imgSrc = goodImgSrcDTO == null ? "" : goodImgSrcDTO.ImgSrc;

        //        listUserCollectModels.Add(new UserCollectModel { Good = good, GoodImgSrc = imgSrc, CollectId = collectIds[index++] });
        //    }

        //    return listUserCollectModels.ToArray();
        //    #endregion
        //}

        //private UserOrderRecordModel[] GetOrderRecords(long userId,HttpContextBase httpContext)
        //{
        //    long userid = UserHelper.GetUserId(httpContext);

        //    int count = 0;

        //    #region 获取用户30天的订单数据

        //    var orders = OrderService.GetUserOrderToDay(userid, 30);

        //    if (orders == null)
        //    {
        //        ViewBag.OrderRecordCount = 0;
        //        return new UserOrderRecordModel[] { };
        //    }


        //    //long[] orderIds = orders.Select(o => o.Id).ToArray();


        //    var orderRecords = GetUserOrderRecor(orders, out count);

        //    ViewBag.OrderRecordCount = count;

        //    return orderRecords;
        //    #endregion
        //}

        ///// <summary>
        ///// 获取商品订单的商品记录，以及商品图片
        ///// </summary>
        ///// <param name="orders"></param>
        ///// <param name="count"></param>
        ///// <returns></returns>
        //private UserOrderRecordModel[] GetUserOrderRecor(OrderDTO[] orders, out int count)
        //{
        //    count = 0;
        //    List<UserOrderRecordModel> listModel = new List<UserOrderRecordModel>();

        //    //遍历我的订单
        //    foreach (var order in orders)
        //    {
        //        //获取订单下的订单记录来
        //        OrderRecordDTO[] orderRecordDTOs = OrderRecordService.GetOrderRecordByOrderId(order.Id);

        //        List<string> listImgSrcs = new List<string>();

        //        foreach (var orderRe in orderRecordDTOs)
        //        {
        //            count++;
        //            //获取订单记录里的商品图片
        //            GoodImgSrcDTO goodImgSrcDTO = GoodImsSrcService.GetFirstImgByGoodId(orderRe.GoodId);

        //            string imgSrc = goodImgSrcDTO == null ? "" : goodImgSrcDTO.ImgSrc;

        //            listImgSrcs.Add(imgSrc);
        //        }

        //        listModel.Add(new UserOrderRecordModel { Order = order, OrderRecord = orderRecordDTOs, ImgSrcs = listImgSrcs.ToArray() });
        //    }

        //    return listModel.ToArray();
        //}
    }
}